package org.kernely.ui;

import java.util.Hashtable;

import org.kernely.core.service.KernelyBundleService;
import org.kernely.web.ContextServiceInterface;
import org.ops4j.pax.web.service.WebContainer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

/**
 * Bundle's Activator
 */
public class Activator implements BundleActivator {

	/**
	 * Called when the bundle is STARTING
	 */
	public final void start(BundleContext pBundleContext) throws Exception {
		ServiceReference refContainer = pBundleContext.getServiceReference("org.ops4j.pax.web.service.WebContainer");
		WebContainer http = (WebContainer) pBundleContext.getService(refContainer);
		ServiceReference refContext = pBundleContext.getServiceReference(ContextServiceInterface.class.getName());
		ContextServiceInterface contextService = (ContextServiceInterface) pBundleContext.getService(refContext);

		Hashtable<String, String> props = new Hashtable<String, String>();
		props.put("init.message", "Main Application Starting");
		MainApplication.VaadinServlet servlet = new MainApplication.VaadinServlet();
		String[] urlPatterns = {"/*", "/VAADIN/*"};
		http.registerServlet(servlet, urlPatterns, props, contextService.getContext());

		// Retrieve KernelyBundleService service
		ServiceReference ref = pBundleContext.getServiceReference(KernelyBundleService.class.getName());
		if (ref != null) {
			KernelyBundleService service = (KernelyBundleService) pBundleContext.getService(ref);
			MainApplication.setCoreService(service);
		}
	}

	/**
	 * Called when the bundle is STOPPING
	 */
	public final void stop(BundleContext context) throws Exception {
	}
}
